import { formFieldMixin } from './formField'
/**
 * Checkbox & Radio & Switch
 */
export const selectionBoxMixin = {
  mixins: [formFieldMixin],
  props: {
    /**
     * 可选值：prefix|suffix
     * 控制Icon与label的排序
     * suffix：Icon在前，label在后
     * prefix与suffix排序相反
     */
    fix: {
      type: String,
      default: 'suffix' // enum: [prefix|suffix]
    },
    falseIcon: String,
    trueIcon: String,
    /**
     * 可选值：round
     * 控制Checkbox & Radio的Icon
     */
    // shape: String, // enum: [round]
    /**
     * name原生的value
     */
    name: {
      type: [String, Number, Boolean],
      required: true
    },
    /**
     * 非必填项
     */
    label: {
      type: [String, Number, Boolean],
      default: ''
    },
    /**
     * option的集合
     */
    options: Array,
    /**
     * 已选中元素value的集合
     */
    value: [Array, String, Number, Boolean]
  },
  computed: {
    _hasSlots() {
      return this.$slots && this.$slots.default
    },
    _trueIcon() {
      return this.trueIcon
    },
    _falseIcon() {
      return this.falseIcon
    }
  },
  methods: {
    _onInnerIntercept (onChange, checkedVals, diff) {
      this._onBaseIntercept((onChangeAfter) => {
        // 执行v-model
        onChange()
        let { name, label, $slots, options } = this
        if (this._hasSlots) {
          label = getText($slots.default)
        }
        options = options || [{ value: name, label }]
        const checkedOptions = diff(options)
        onChangeAfter(checkedVals, checkedOptions)
      }, checkedVals)
    },
    _onCheckboxIntercept(onChange, checkedVals) {
      this._onInnerIntercept(onChange, checkedVals, options => {
        // TODO 此处存在漏洞，即：1和‘1’是判断不出来的
        const valString = `;${checkedVals.join(';')};`
        return options.filter(it => valString.indexOf(it.value) > 0)
      })
    },
    _onRadioIntercept(onChange, val) {
      this._onInnerIntercept(onChange, val, options => {
        /* eslint-disable eqeqeq */
        return options.find(it => (this.strict ? it.value === val : it.value == val))
      })
    }
  },
  render(h) {
    const { _isChecked, _trueIcon, _falseIcon, disabled, _hasSlots, $slots, label } = this
    const clz = ['iconfont', `${_isChecked ? _trueIcon : _falseIcon}`]
    const children = [h('span', { 'class': clz })]

    if (this.fix === 'prefix') {
      children.unshift(h('span', { 'class': 'polyfill-mr' }, _hasSlots ? $slots.default : label))
    } else {
      children.push(h('span', { 'class': 'polyfill-ml' }, _hasSlots ? $slots.default : label))
    }
    return h(
      'div',
      { on: { click: this._onInnerClick }, 'class': `${this._class}${this._display} ${disabled && `${this._class}-disabed`}` },
      children
    )
  }
}

function getText(nodes) {
  const [vnode] = nodes
  if (vnode && vnode.text) {
    return vnode.text
  }
  return getText(vnode.children)
}
